<template>
  <view class="leave-record-page">
    <!-- 筛选栏 -->
    <view class="filter-section">
      <u-tabs
        :list="filterTabs"
        :current="currentFilter"
        @change="handleFilterChange"
        lineWidth="30"
        lineHeight="3"
        activeStyle="color: #2d8cf0; font-weight: bold;"
        inactiveStyle="color: #606266;"
      ></u-tabs>
    </view>

    <!-- 请假记录列表 -->
    <scroll-view 
      scroll-y="true" 
      class="leave-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="leave-list">
        <view
          v-for="leave in leaveList"
          :key="leave.id"
          class="leave-item"
          @click="handleLeaveDetail(leave)"
        >
          <view class="leave-header">
            <view class="leave-type">
              <u-tag
                :text="getLeaveTypeText(leave.leaveType)"
                :type="getLeaveTypeType(leave.leaveType)"
                size="small"
              ></u-tag>
            </view>
            <view class="leave-status">
              <u-tag
                :text="getStatusText(leave.status)"
                :type="getStatusType(leave.status)"
                size="small"
              ></u-tag>
            </view>
          </view>
          
          <view class="leave-content">
            <view class="leave-dates">
              <view class="date-item">
                <u-icon name="calendar" size="14" color="#2d8cf0"></u-icon>
                <text class="date-text">{{ formatDate(leave.startDate) }} - {{ formatDate(leave.endDate) }}</text>
              </view>
              <view class="date-item">
                <u-icon name="clock" size="14" color="#ff9500"></u-icon>
                <text class="date-text">{{ leave.days || leave.duration || 0 }}{{ leave.days ? '天' : '小时' }}</text>
              </view>
            </view>
            
            <view class="leave-reason">
              <text class="reason-text">{{ leave.reason }}</text>
            </view>
          </view>
          
          <view class="leave-footer">
            <text class="create-time">{{ formatDateTime(leave.createTime) }}</text>
            <view class="footer-actions">
              <!-- 待审批状态显示审批按钮 -->
              <view v-if="leave.status === 1" class="approve-actions">
                <u-button 
                  type="primary" 
                  size="mini" 
                  text="审批"
                  :custom-style="{ marginRight: '8px' }"
                  @click.stop="handleApprove(leave)"
                ></u-button>
              </view>
              <!-- 其他状态显示箭头 -->
              <u-icon v-else name="arrow-right" size="16" color="#ccc"></u-icon>
            </view>
          </view>
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="leaveList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-if="leaveList.length === 0 && !loading" class="empty-state">
      <u-empty
        text="暂无请假记录"
        mode="data"
      ></u-empty>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <u-loading-icon mode="spinner"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 浮动添加按钮 -->
    <view class="fab-button" @click="handleAddLeave">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
    </view>

    <!-- 审批弹窗已移除，改为跳转到专门页面 -->
  </view>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue'
import { getLeavePage } from '@/api/leave'
import { useAuthStore } from '@/store/auth'

export default {
  name: 'LeaveRecord',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const refreshing = ref(false)
    const currentFilter = ref(0)
    const leaveList = ref([])
    const hasMore = ref(true)
    
    // 审批相关数据（已移除弹窗，改为跳转页面）

    // 分页参数
    const pagination = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0
    })

    // 筛选标签
    const filterTabs = ref([
      { name: '全部', status: null },
      { name: '待审批', status: 1 },
      { name: '已批准', status: 2 },
      { name: '已拒绝', status: 3 }
    ])

    // 获取请假类型文本
    const getLeaveTypeText = (type) => {
      // 支持字符串类型和数字类型
      const typeMap = {
        'personal': '事假',
        'sick': '病假', 
        'annual': '年假',
        'compensatory': '调休',
        'maternity': '产假',
        'paternity': '陪产假',
        'other': '其他',
        // 数字类型映射
        0: '事假',
        1: '病假',
        2: '年假',
        3: '调休'
      }
      return typeMap[type] || typeMap[type?.toString()] || '未知'
    }

    // 获取请假类型样式
    const getLeaveTypeType = (type) => {
      const typeMap = {
        'personal': 'primary',
        'sick': 'warning',
        'annual': 'success',
        'compensatory': 'info',
        'maternity': 'error',
        'paternity': 'error',
        'other': 'default',
        // 数字类型映射
        0: 'primary',
        1: 'warning',
        2: 'success',
        3: 'info'
      }
      return typeMap[type] || typeMap[type?.toString()] || 'default'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        1: '待审批',
        2: '已批准',
        3: '已拒绝',
        4: '已撤销'
      }
      return statusMap[status] || '未知'
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        1: 'warning',
        2: 'success',
        3: 'error',
        4: 'info'
      }
      return typeMap[status] || 'default'
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const d = new Date(dateTime)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }

    // 加载请假记录
    const loadLeaveList = async (isRefresh = false) => {
      try {
        if (isRefresh) {
          refreshing.value = true
          pagination.pageNum = 1
          leaveList.value = []
          hasMore.value = true
        } else {
          loading.value = true
        }

        // 检查用户物业公司关联状态
        const authStore = useAuthStore()
        const userInfo = authStore.userInfo
        console.log('当前用户信息:', userInfo)
        console.log('用户物业公司ID:', userInfo?.propertyCompanyId)
        console.log('用户角色:', userInfo?.roles)
        console.log('用户类型:', userInfo?.userType)

        // 构建查询参数
        const queryParams = {
          pageNum: pagination.pageNum,
          pageSize: pagination.pageSize,
          status: filterTabs.value[currentFilter.value].status
        }

        console.log('加载请假记录，查询参数:', queryParams)

        // 调用API获取请假记录
        const result = await getLeavePage(queryParams)
        
        console.log('请假记录API响应结果:', result)
        console.log('API响应success:', result.success)
        console.log('API响应data:', result.data)
        console.log('API响应message:', result.message)
        
        if (result.success && result.data) {
          const { records, total, current, size } = result.data
          
          console.log('请假记录数据详情:')
          console.log('- records:', records)
          console.log('- total:', total)
          console.log('- current:', current)
          console.log('- size:', size)
          
          if (isRefresh || pagination.pageNum === 1) {
            leaveList.value = records || []
          } else {
            leaveList.value = [...leaveList.value, ...(records || [])]
          }
          
          pagination.total = total || 0
          pagination.pageNum = current || pagination.pageNum
          pagination.pageSize = size || pagination.pageSize
          
          // 判断是否还有更多数据
          hasMore.value = leaveList.value.length < pagination.total
          
          console.log('请假记录加载成功，总数:', pagination.total, '当前页数据:', records?.length)
        } else {
          console.error('加载请假记录失败:', result.message)
          console.error('失败原因分析:')
          console.error('- success:', result.success)
          console.error('- data:', result.data)
          console.error('- message:', result.message)
          
          // 检查是否是权限问题
          if (result.message && result.message.includes('权限')) {
            uni.showToast({
              title: '您没有权限查看请假记录',
              icon: 'none',
              duration: 3000
            })
          } else {
            uni.showToast({
              title: result.message || '加载失败',
              icon: 'none'
            })
          }
        }
      } catch (error) {
        console.error('加载请假记录异常:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }

    // 筛选变化
    const handleFilterChange = (index) => {
      currentFilter.value = index
      console.log('筛选变化:', filterTabs.value[index].name)
      // 重新加载数据
      loadLeaveList(true)
    }

    // 加载更多数据
    const loadMore = () => {
      if (!hasMore.value || loading.value) {
        return
      }
      pagination.pageNum += 1
      loadLeaveList()
    }

    // 下拉刷新
    const onRefresh = () => {
      loadLeaveList(true)
    }

    // 查看请假详情
    const handleLeaveDetail = (leave) => {
      uni.navigateTo({
        url: `/pages/property-work/leave-detail?id=${leave.id}`
      })
    }

    // 添加请假申请
    const handleAddLeave = () => {
      uni.navigateTo({
        url: '/pages/property-work/leave-apply'
      })
    }

    // 处理审批
    const handleApprove = (leave) => {
      console.log('开始审批请假申请:', leave)
      
      // 跳转到审批页面
      uni.navigateTo({
        url: `/pages/property-work/leave-approve?id=${leave.id}`,
        success: () => {
          console.log('跳转到审批页面成功')
        },
        fail: (error) => {
          console.error('跳转到审批页面失败:', error)
          uni.showToast({
            title: '页面跳转失败',
            icon: 'none'
          })
        }
      })
    }

    // 审批相关方法已移除，改为跳转到专门页面

    // 检查用户物业公司关联状态（简化版本）
    const checkUserPropertyCompanyStatus = async () => {
      try {
        console.log('检查用户物业公司关联状态...')
        
        // 检查本地存储的用户信息
        const authStore = useAuthStore()
        const userInfo = authStore.userInfo
        console.log('本地用户信息:', userInfo)
        
        // 后端数据权限机制会自动处理物业公司筛选，无需前端额外检查
        // 如果用户没有权限，API会返回空数据或相应错误信息
        return true
      } catch (error) {
        console.error('检查用户物业公司关联状态失败:', error)
        return false
      }
    }

    // 页面加载
    onMounted(async () => {
      // 直接加载请假记录，后端数据权限机制会自动处理物业公司筛选
      loadLeaveList()
    })

    return {
      loading,
      refreshing,
      currentFilter,
      leaveList,
      hasMore,
      pagination,
      filterTabs,
      getLeaveTypeText,
      getLeaveTypeType,
      getStatusText,
      getStatusType,
      formatDate,
      formatDateTime,
      handleFilterChange,
      handleLeaveDetail,
      handleAddLeave,
      loadMore,
      onRefresh,
      // 审批相关
      handleApprove
    }
  }
}
</script>

<style lang="scss" scoped>
.leave-record-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  position: relative;
}

.filter-section {
  flex-shrink: 0;
  background: #fff;
  padding: 0 30rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.leave-scroll {
  flex: 1;
  min-height: 0;
  height: calc(100vh - 120rpx); // 减去筛选栏的高度
}

.leave-list {
  padding: 20rpx 30rpx 120rpx; // 底部增加间距，避免被浮动按钮遮挡
  
  .leave-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.98);
    }
    
    .leave-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
    }
    
    .leave-content {
      margin-bottom: 20rpx;
      
      .leave-dates {
        display: flex;
        margin-bottom: 15rpx;
        
        .date-item {
          display: flex;
          align-items: center;
          margin-right: 30rpx;
          
          .date-text {
            margin-left: 8rpx;
            font-size: 26rpx;
            color: #666;
          }
        }
      }
      
      .leave-reason {
        .reason-text {
          font-size: 28rpx;
          color: #333;
          line-height: 1.5;
        }
      }
    }
    
    .leave-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .create-time {
        font-size: 24rpx;
        color: #999;
      }
      
      .footer-actions {
        display: flex;
        align-items: center;
        
        .approve-actions {
          display: flex;
          align-items: center;
        }
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.loading-state {
  padding: 100rpx 0;
  text-align: center;
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.fab-button {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  background: #2d8cf0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(45, 140, 240, 0.3);
  z-index: 100;
}

// 审批弹窗样式已移除，改为跳转到专门页面

// 响应式适配
</style>
